#! /bin/bash

set -euo pipefail

function fs_usage() {
  local fs_name=${1:?missing filesystem name}
  df -h | grep ${fs_name} | awk '{ print $3 "/" $2 "\t" $5 }'
}

readonly log_dir=/var/log/sync_backup
mkdir -p $log_dir

readonly date_str=$(date '+%Y-%m-%d')
readonly log_file=${log_dir}/${date_str}.log

if ! ( mountpoint -q /mnt/secondary_disk && mountpoint -q /mnt/primary_disk );
then
  echo "at least one disk not mounted"

  msmtp feedem_F@163.com <<END
Subject: ${date_str} nas backup FAILED!

device not mounted
END

  exit 1
fi

readonly sync_out=$(rsync -av --delete /mnt/primary_disk/ /mnt/secondary_disk 2>&1)
readonly succeeded=$?

cat <<< "${sync_out}" > ${log_file}

if [[ $succeeded -eq 0 ]]
then
  msmtp feedem_F@163.com <<END
Subject: ${date_str} nas backup report

job done
primary disk usage:   $(fs_usage /mnt/primary_disk)
secondary disk usage: $(fs_usage /mnt/secondary_disk)
log file at:          ${log_file}
END
else
  msmtp feedem_F@163.com <<END
Subject: ${date_str} nas backup ERROR!

log file at:          ${log_file}
END
fi


